package miniprogram

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

type API struct {
	AppID  string
	Secret string
}

type APIReutrns struct {
	Success   bool
	Message   string
	ErrorCode float64
	Response  map[string]interface{}
}

func NewAPI() *API {
	// https://mp.weixin.qq.com/wxamp/wadevelopcode/sandbox?token=1730148433&lang=zh_CN
	var api = API{
		AppID:  "wxca381753ba3dd5f7",
		Secret: "0388a242f826f5a4065345ecd99826f0",
	}
	return &api
}

func (api *API) ToJSON(content []byte) APIReutrns {
	var jsonmap map[string]interface{}
	json.Unmarshal(content, &jsonmap)

	var res = APIReutrns{}

	if errcode, ok := jsonmap["errcode"]; ok {
		res.Success = false
		res.ErrorCode = errcode.(float64)
		res.Message = jsonmap["errmsg"].(string)
		return res
	}

	res.Success = true
	res.Response = jsonmap
	res.ErrorCode = 0
	res.Message = ""
	return res
}

func (api *API) JSCode2Session(code string) APIReutrns {
	var url = `https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code`
	url = fmt.Sprintf(url, api.AppID, api.Secret, code)

	resp, err := http.Get(url)
	if err != nil {
		log.Println("JsApiTicket 请求微信官方接口 ticket/getticket 时出错：", err.Error())

	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)

	return api.ToJSON(body)
}
